package cn.chencq.collection.list;

public class MyArrayList {

	private Object[] elementData;
	private int size;

	public MyArrayList() {
		this(10);
	}

	public MyArrayList(int initialCapacity) {
		if (initialCapacity < 0) {
			try {
				throw new Exception();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		elementData = new Object[initialCapacity];
	}
	
	public int size() {
		return size;
	}

	public boolean isEmpty() {
		return size == 0;
	}

	public void add(Object obj) {
		ensureCapacity();
		elementData[size++] = obj;
	}

	public Object get(int index) {
		rangeCheck(index);
		return elementData[index];
	}

	private void rangeCheck(int index) {
		if (index < 0 || index >= size) {
			throw new IndexOutOfBoundsException("Index: " + index + ", Size: "+ size);
		}
	}
	
	public void remove(int index) {
		rangeCheck(index);
		int numMoved = size - index - 1;
		if (numMoved > 0) {
			System.arraycopy(elementData, index + 1, elementData, index,numMoved);
		}
		elementData[--size] = null;
	}

	public void remove(Object obj) {
		for (int i = 0; i < size; i++) {
			if (get(i).equals(obj)) {
				remove(i);
			}
		}
	}

	public Object set(int index, Object obj) {
		rangeCheck(index);
		Object oldValue = elementData[index];
		elementData[index] = obj;
		return oldValue;
	}

	// add element 
	public void add(int index, Object obj) {
		rangeCheck(index); 
		ensureCapacity();
		System.arraycopy(elementData, index, elementData, index + 1, size- index);
		elementData[index] = obj;
		size++;
	}

	private void ensureCapacity() {
		if (size == elementData.length) {
			Object[] newArray = new Object[size * 2 + 1];
			System.arraycopy(elementData, 0, newArray, 0, elementData.length);
			elementData = newArray;
		}
	}

	public static void main(String[] args) {
		MyArrayList slist = new MyArrayList(3);
		slist.add("aaa");
		slist.add("bbb");
		slist.add("ccc");
		slist.add("ddd");
		slist.add("eee");
		slist.add("fff");
		slist.add("ggg");
		slist.add("hhh");
		slist.add("jjj");
		System.out.println(slist.size());
		System.out.println(slist.get(1));
		slist.remove(1);
		slist.add(4, "444");
		System.out.println("after remove......");
		System.out.println(slist.size());
		System.out.println(slist.get(4));
	}
}
